<template>
	<view class="viewBg">
		<view class="uni-list">
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					日志标题
				</view>
				<view class="uni-list-cell-db">
					<!-- 日志标题 -->
					<input class="uni-input" placeholder="日志标题" :value="formItem.log_title" @blur="bindInputLogTitleBlur" @focus="hiddenText"/>
				</view>
			</view>
		</view>
		
		<!-- 记录时间 -->
		<view class="uni-list">
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					记录时间
				</view>
				<view class="uni-list-cell-db">
					<picker mode="date" placeholder="记录时间" :value="formItem.create_time" :start="startDate" :end="endDate" @change="bindDateChange">
						<view class="uni-input">{{ formItem.create_time }} </view>
					</picker>
				</view>
			</view>
		</view>
		
		<view class="lineH1"></view>

		<!-- 列表 -->
		<view class="uni-list">
			<view class="uni-list-cell" v-for="(item, index) in list" :key="index">
				<view class="uni-list-cell-navigate uni-navigate-right" @click="showPicker(index)">
					<text class="cell-text">{{ item.title }}</text>
					<text class="cell-detail">{{ item.selectedLabel }}</text>
				</view>
			</view>
		</view>
		
		<view class="uni-list">
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					工作对象名称
				</view>
				<view class="uni-list-cell-db">
					<input class="uni-input" placeholder="工作对象名称" :value="formItem.work_obj_name" @blur="bindInputWorkObjNameBlur" @focus="hiddenText"/>
				</view>
			</view>
		</view>
		<view class="uni-list">
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					工作对象联系电话
				</view>
				<view class="uni-list-cell-db">
					<input class="uni-input" placeholder="工作对象联系电话" :value="formItem.work_obj_tel" @blur="bindInputWorkObjTelBlur" @focus="hiddenText"/>
				</view>
			</view>
		</view>
		
		<!-- 分割线 -->
		<view class="lineH20"></view>
		
		<view class="uni-list">
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					责任人
				</view>
				<view class="uni-list-cell-db">
					<input class="uni-input" placeholder="责任人" :value="formItem.responsibility_person" @blur="bindInputResponsibilityPersonBlur" @focus="hiddenText"/>
				</view>
			</view>
		</view>
		<view class="uni-list">
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					责任人电话
				</view>
				<view class="uni-list-cell-db">
					<input class="uni-input" placeholder="责任人电话" :value="formItem.responsibility_person_mobile" @blur="bindInputResponsibilityPersonMobileBlur" @focus="hiddenText"/>
				</view>
			</view>
		</view>

		<view class="lineH1"></view>
		<!-- 详细描述 -->
		<view class="uni-textarea">
			<textarea placeholder="日志内容" :value="formItem.log_info" @blur="bindLogInfoBlur" @focus="hiddenText"/>
		</view>
		<view class="uni-list">
			<view class="uni-list-cell">
				<view class="uni-list-cell-navigate uni-navigate-right" @click="seleceLocation">
					<text class="cell-text" style="max-width: 600upx">{{address}}</text>
					<text class="cell-detail" v-if="location === null" style="width: 100upx">请选择</text>
					<text class="cell-detail" v-if="location !== null" style="width: 100upx">已选择</text>
				</view>
			</view>
		</view>
		<!-- 上传图片 -->
		<view class="feedback-body feedback-uploader">
			<view class="uni-uploader">
				<view class="uni-uploader-head">
					<view class="uni-uploader-title">点击上传图片</view>
					<view class="uni-uploader-info">{{ imageList.length }}/6</view>
				</view>
				<view class="uni-uploader-body">
					<view class="uni-uploader__files">
						<block v-for="(image, index) in imageList" :key="index">
							<view class="uni-uploader__file" style="position: relative;">
								<image class="uni-uploader__img" :src="image" @tap="previewImage(index)"></image>
								<view class="close-view" @click="close(index)">x</view>
							</view>
						</block>
						<view class="uni-uploader__input-box" v-show="imageList.length < 6">
							<view class="uni-uploader__input" @tap="chooseImg"></view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- <view class="button-sp-area" v-if="videoPath === null">
			<button type="default" plain="true" @click="chooseVideo">上传视频</button>
		</view>
		<view class="" v-if="videoPath && videoShow">
            <video :src="videoPath" controls :show-center-play-btn="true"></video>
            <view class="">
                <button type="warn" size="mini" @click="videoPath=null">删除</button>
            </view>
        </view> -->
		<view class="lineH1"></view>

		<!-- <button type="primary" @tap="createParams('0')" :disabled="buttonDisable" v-if="eventId === null && hiddenButton!=3 && Lhidden">保存草稿</button> -->
		<button type="primary" @tap="createParams('2')" :disabled="buttonDisable" v-if="hiddenButton==1 || hiddenButton ==3 && Lhidden">保存日志</button>
		<!-- <button type="primary" @tap="createParams('1')" :disabled="buttonDisable" v-if="hiddenButton==2 || hiddenButton ==3  && Lhidden">上报网格长</button> -->
		<mpvue-picker
			:themeColor="themeColor"
			ref="mpvuePicker"
			:mode="mode"
			:deepLength="deepLength"
			:pickerValueDefault="pickerValueDefault"
			@onConfirm="onConfirm"
			@onCancel="onCancel"
			:pickerValueArray="pickerValueArray"
		></mpvue-picker>
	</view>
</template>

<script>
import mpvuePicker from '@/components/mpvue-picker/mpvuePicker.vue';
import amap from '../../../common/amap-wx.js';
import { pathToBase64, base64ToPath } from '../../../common/image-tools/index.js'
export default {
	components: { mpvuePicker },
	data() {
		const currentDate = this.getDate({format: true})
		return {
			list: [
				{ title: '所属区', value: null, selectedLabel: '请选择', selectedValue: '0' },
				{ title: '所属街道', value: null, selectedLabel: '请选择', selectedValue: '0' },
				{ title: '所属社区', value: null, selectedLabel: '请选择', selectedValue: '0' },
				{ title: '日志类型', value: null, selectedLabel: '请选择', selectedValue: '0' },
				{ title: '工作类型', value: null, selectedLabel: '请选择', selectedValue: '0' },
				{ title: '工作对象类型', value: null, selectedLabel: '请选择', selectedValue: '0' },
			],
			
			themeColor: '#007AFF',
			pickerValueDefault: [0],
			mode: '',
            address:'选择地址位置',
			pickerValueArray: [],
			selectIndex: '',
			imageList: [],
			videoPath: null,
			eventTitle: '',
			eventDesc: '',
			uploadFileHeader: {},
			location: null,
			eventId: null,
			hiddenButton: true,
			deepLength: 1,
			videoShow: true,
            buttonDisable:false,
            Lhidden : true,
			amapPlugin: null,
			mapKey: 'fbb5ddc12d6183eba23f27639f49757a',
			// 开始后台传值
			formItem: {
				log_title: '',
				create_time: currentDate,
				work_obj_name: '',
				work_obj_tel: '',
				responsibility_person: '',
				responsibility_person_mobile: '',
				log_info: '',
				log_status: '',
				work_status: '',
				work_obj_status: '',
				city: '',
				street: '',
				cummunity: '',
				question_img: ''
			},
			
			// 上传hadoop相关
			upPicData: {
				filePath: '',
				fileName: ''
			},
			fileUrlList: [],
			timeStep: '',
			index1: 0
		};
	},
	computed: {
		startDate() {
			return this.getDate('start');
		},
		endDate() {
			return this.getDate('end');
		}
	},
	onLoad(event) {
		
		uni.getLocation({
		    type: 'gcj02',
		    success: function (res) {
		        // alert('当前位置的经度：' + res.longitude);
		        // alert('当前位置的纬度：' + res.latitude);
				console.log('获取位置:' + JSON.stringify(res));
				that.location = {
					longitude: res.longitude,
					latitude: res.latitude
				};
				that.address = '无地址'
		    },
			fail: function(error) {
				console.log('获取位置错误:' + JSON.stringify(error));
			}
		});
		console.log('这是用户信息 ' + getApp().globalData.userInfo);
        this.hiddenButton = event.btn;
        if(event.btn == 1) {
	        uni.setNavigationBarTitle({
		        title: '日志内容'
	        });
        }
		var that = this;
		uni.getStorage({
			key: 'accessToken',
			success: function(res) {
				that.uploadFileHeader = { scpid: 'bearer.' + res.data };
			},
			fail: function(error) {
			}
		});

		if (event.id) {
			this.eventId = event.id;
			console.log('这里有id' + event.id);
			this.loadDraftData(event.id);
		}
	},
	methods: {
		bindDateChange: function(e) {
			this.formItem.create_time = e.target.value
		},
		// 获取定位信息
		seleceLocation() {
			var that = this;
			this.$eventHub.$on('fire', function(data) {
				console.log('消息回掉' + JSON.stringify(data));
				that.location = {
					latitude: data.latitude,
					longitude: data.longitude
				};
				that.address = data.address
				that.$eventHub.$off('fire');
			});
			if (that.location === null) {
				uni.navigateTo({
					url: '/pages/map/selectEventLocation/selectEventLocation'
				});
			} else {
				uni.navigateTo({
					url: '/pages/map/selectEventLocation/selectEventLocation?latitude=' + that.location.latitude + '&longitude=' + that.location.longitude
				});
			}
		},
		getCity(parent_id,index) {
			this.$http.post('as/xagrid/applog/selectcitylist', { parent_id: parent_id }).then(res => {
				console.log('res.data.data.data.dtatatata: ', res.data)
				this.list[index].value = res.data;
				this.list[index].value.unshift({ label: '请选择', value: '' })
				this.pickerValueArray = this.list[index].value;
				this.$refs.mpvuePicker.show();
			});
		},
		showPicker(index) {
			this.videoShow = false;
			let type = '';
			let id = '';
			let targetstype = '';
			// for (var i = 0; i < this.list.length; i++) {
			// 	var item = this.list[i];
			// 	if (item.title === '事件类型') {
			// 		params.eventType = String(item.selectedValue);
			// 	} else if (item.title === '所属区') {
			// 		params.city = String(item.selectedValue);
			// 	} else if (item.title === '所属街道') {
			// 		params.street = String(item.selectedValue);
			// 	} else if (item.title === '所属社区') {
			// 		params.cummunity = String(item.selectedValue);
			// 	} else if (item.title === '日志状态') {
			// 		params.log_status = String(item.selectedValue);
			// 	} else if (item.title === '工作类别') {
			// 		params.work_status = String(item.selectedValue);
			// 	} else if (item.title === '工作对象类别') {
			// 		params.work_obj_status = String(item.selectedValue);
			// 	}
			// }
			if (this.list[index].title == '所属区') {
				this.getCity('',index);
			} else if (this.list[index].title == '所属街道') {
				this.getCity(String(this.list[0].selectedValue),index);
			} else if (this.list[index].title == '所属社区') {
				this.getCity(String(this.list[1].selectedValue),index);
			}
			
			if (this.list[index].title == '工作类型') {
				type = 'work_status';
			}
			if (this.list[index].title == '工作对象类型') {
				type = 'work_obj_status';
			}
			if (this.list[index].title == '日志类型') {
				type = 'log_status';
			}
			if (type.length > 0 && !this.list[index].value) {
				this.$http.get('ac/xagrid/appDictService/getDictItems', { type: type }).then(res => {
					this.list[index].value = res.data;
					this.list[index].value.unshift({ label: '请选择', value: '' })
					this.pickerValueArray = this.list[index].value;
					this.$refs.mpvuePicker.show();
				});
			} else {
				if (!this.list[index].value) {
					let self = this;
					id = self.list[2].selectedValue;
					targetstype = self.list[2].selectedValue;
				} else {
					this.pickerValueArray = this.list[index].value;
					this.$refs.mpvuePicker.show();
				}
			}
			this.selectIndex = index;
			this.mode = 'selector';
			this.pickerValueDefault = [0];
		},
		onConfirm(e) {
			this.videoShow = true;
			this.list[this.selectIndex].selectedLabel = e.label;
			this.list[this.selectIndex].selectedValue = e.value;
		},
		onCancel() {
			this.videoShow = true;
		},
		previewImage(index) {
			//预览图片
			uni.previewImage({
				current: this.imageList[index],
				urls: this.imageList
			});
		},
		close(e) {
			this.imageList.splice(e, 1);
			this.formItem.question_img.split(',').splice(e,1)
		},
		// 选择图片的时候
		chooseImg() {
			//选择图片
			uni.chooseImage({
				sourceType: ['camera', 'album'],
				sizeType: 'compressed',
				count: 6 - this.imageList.length,
				success: res => {
					// this.imageList = this.imageList.concat(res.tempFilePaths);
					// this.urlTobase64(res.tempFilePaths[0], res.tempFiles[0])				
					console.log('选择图片了', JSON.stringify(res));
					pathToBase64(res.tempFilePaths[0]).then(base64 => {
						// console.log(base64);
						this.beforeUpload(res.tempFiles[0], base64)
					 })
					 .catch(error => {
						console.error(error);
					 });
					// uni.request({
					// 	url: 'file:///storage/emulated/0/MagazineUnlock/magazine-unlock-03-2.3.5962-_C766F8CB268242F948DD4F86EAF803B1.jpg',//res.tempFilePaths[0],
					// 	method:'GET',
					// 	responseType: 'arraybuffer',
					// 	success: ress => {
					// 		console.log('ress.data: ', ress.data)
					// 		let base64 = wx.arrayBufferToBase64(ress.data); //把arraybuffer转成base64 
					// 		base64 = 'data:image/jpeg;base64,' + base64 //不加上这串字符，在页面无法显示的哦
					// 		// console.log('66666666666666666:  === : ', base64)
							
					// 		this.beforeUpload(res.tempFiles[0], base64)
					// 	},
					// })
				}
			});
		},
		// 作废了
		urlTobase64(url, files){
			let that = this
			console.log('uni is go')
		    uni.request({
				url: url,
				method:'GET',
				responseType: 'arraybuffer',
				success: ress => {
					let base64 = wx.arrayBufferToBase64(ress.data); //把arraybuffer转成base64 
					base64 = 'data:image/jpeg;base64,' + base64 //不加上这串字符，在页面无法显示的哦
					console.log('66666666666666666:  === : ', base64)
					
					that.beforeUpload(files, base64)
				}
		    })
		},
		//选择视频
		chooseVideo() {
			var self = this;
			uni.chooseVideo({
				sourceType: ['camera', 'album'],
				success: function(res) {
					self.videoPath = res.tempFilePath;
				}
			});
		},
		bindInputLogTitleBlur(e) {
            this.Lhidden = true
			this.formItem.log_title = e.detail.value;
			console.log('事件标题' + this.eventTitle);
		},
		bindInputWorkObjNameBlur(e) {
            this.Lhidden = true
			this.formItem.work_obj_name = e.detail.value;
		},
		bindInputWorkObjTelBlur(e) {
		    this.Lhidden = true
			this.formItem.work_obj_tel = e.detail.value;
		},
		bindInputResponsibilityPersonBlur(e) {
		    this.Lhidden = true
			this.formItem.responsibility_person = e.detail.value;
		},
		bindInputResponsibilityPersonMobileBlur(e) {
		    this.Lhidden = true
			this.formItem.responsibility_person_mobile = e.detail.value;
		},
		bindLogInfoBlur(e) {
		    this.Lhidden = true
			this.formItem.log_info = e.detail.value;
		},
        hiddenText:function(){
            this.Lhidden = false
        },
        //按钮设置不可以点击状态
        buttonFun(){
			// this.buttonDisable = !this.buttonDisable
        },
		// 处理参数
		createParams(status) {
			this.buttonFun()
			var that = this;
			var params = new Object();
			
			if (that.formItem.log_title.length === 0) {
				uni.showModal({
					title: '提示',
					content: '请输入日志标题',
					showCancel: false
				});
			    this.buttonFun()
				return;
			} else {
				params.log_title = that.formItem.log_title;
			}
			if (that.formItem.create_time.length === 0) {
				uni.showModal({
					title: '提示',
					content: '请选择记录时间',
					showCancel: false
				});
			    this.buttonFun()
				return;
			} else {
				params.create_time = that.formItem.create_time;
			}
			//校验数据
			for (var i = 0; i < this.list.length; i++) {
				var item = this.list[i];
				if (item.selectedLabel === '请选择' && item.title !== '所属社区') {
					uni.showModal({
						title: '提示',
						content: '请选择' + item.title,
						showCancel: false
					});
                    this.buttonFun()
					return;
				} else {
					if (item.title === '所属区') {
						params.city = String(item.selectedValue);
					} else if (item.title === '所属街道') {
						params.street = String(item.selectedValue);
					} else if (item.title === '所属社区') {
						if(String(item.selectedValue) == 0) {
							params.cummunity = '';
						}else{
							params.cummunity = String(item.selectedValue);
						}
					} else if (item.title === '日志类型') {
						params.log_status = String(item.selectedValue);
					} else if (item.title === '工作类型') {
						params.work_status = String(item.selectedValue);
					} else if (item.title === '工作对象类型') {
						params.work_obj_status = String(item.selectedValue);
					}
				}
			}
			
			if (!that.formItem.work_obj_name) {
				uni.showModal({
					title: '提示',
					content: '请输入工作对象名称',
					showCancel: false
				});
			    this.buttonFun()
				return;
			} else {
				params.work_obj_name = that.formItem.work_obj_name;
			}
			
			if (!that.formItem.work_obj_tel) {
				uni.showModal({
					title: '提示',
					content: '请输入工作对象联系电话',
					showCancel: false
				});
			    this.buttonFun()
				return;
			} else if (/^[1]{1}[3,5,7,8,9]{1}\d{9}$/g.test(that.formItem.work_obj_tel) === false) {
				uni.showModal({
					title: '提示',
					content: '请输入正确的工作对象联系电话（手机号）',
					showCancel: false
				});
			    this.buttonFun()
				return;
			} else {
				params.work_obj_tel = that.formItem.work_obj_tel;
			}
			
			if (!that.formItem.responsibility_person) {
				uni.showModal({
					title: '提示',
					content: '请输入责任人',
					showCancel: false
				});
			    this.buttonFun()
				return;
			} else {
				params.responsibility_person = that.formItem.responsibility_person;
			}
			
			if (!that.formItem.responsibility_person_mobile) {
				uni.showModal({
					title: '提示',
					content: '请输入责任人电话',
					showCancel: false
				});
			    this.buttonFun()
				return;
			}  else if (/^[1]{1}[3,5,7,8,9]{1}\d{9}$/g.test(that.formItem.responsibility_person_mobile) === false) {
				uni.showModal({
					title: '提示',
					content: '请输入正确的责任人电话（手机号）',
					showCancel: false
				});
			    this.buttonFun()
				return;
			} else {
				params.responsibility_person_mobile = that.formItem.responsibility_person_mobile;
			}

			// if (that.formItem.log_info.length === 0) {
			// 	uni.showModal({
			// 		title: '提示',
			// 		content: '请输入详细说明',
			// 		showCancel: false
			// 	});
   //              this.buttonFun()
			// 	return;
			// } else {
				params.log_info = that.formItem.log_info;
			// }
			
			if (!that.location) {
				uni.showModal({
					title: '提示',
					content: '请选择地址位置',
					showCancel: false
				});
				this.buttonFun()
				return;
			} else {
				params.eventLongitude = that.location.longitude;
				params.eventLatitude = that.location.latitude;
				params.event_address = that.address;
			}
			// params.eventLongitude = '123.414381';
			// params.eventLatitude = '41.813453';
			// params.event_address = '走起地址';
			if (this.imageList.length == 0) {
				uni.showModal({
					title: '提示',
					content: '请上传照片',
					showCancel: false
				});
              this.buttonFun()
				return;
			}

			params.status = status;

			if (this.imageList.length > 0 || this.videoPath !== null) {
				uni.showToast({
					icon: 'none',
					title: '正在上传...',
					mask: true,
					duration: 2000
				});
				params.questionImg = this.formItem.question_img
			}
			
			params.questionVideo = ''
				
			// if (this.imageList.length > 0) {
			// 	console.log('上传图片开始');
			// 	// this.uploadImages(params);
			// } 
			// else if (this.videoPath !== null) {
			// 	console.log('上传视频开始');
			// 	this.uploadVideo(params);
			// } 
	
			console.log('直接提交了');
			that.reportEvent(params);

			console.log('走到这里了' + JSON.stringify(params));
		},
		uploadImages(params) {
			var that = this;
			var oldImages = new Array();
			var images = new Array();
			alert(JSON.stringify(that.imageList))
			for (var i = 0; i < that.imageList.length; i++) {
				images.push({ name: 'images-' + String(i) });
			}
			// let file = {	
			// 	lastModified: 1599792944004
			// 	lastModifiedDate: new Date()
			// 	name: 
			// 	size: 40660
			// 	type: "image/jpeg"
			// 	webkitRelativePath: ""
			// }
			
			// // 新上传图片地址
			// export const createUpLoadFiles = (param) => {
			//   return axios.request({
			//     url: '/api/ac/cscpub/auditHadoopUploadFilesService/createUpLoadFiles',
			//     method: 'post',
			//     data: param
			//   })
			// }
			
			// var time = new Date().getTime()
			// this.timeStep = time.toString()
			// this.upPicData.fileName = this.formItem.log_title + this.timeStep + images[0].name
			// this.upPicData.filePath = this.timeStep
			// const reader = new FileReader()
			// reader.readAsDataURL(file)
			// reader.onload = () => {
			// 	let index = reader.result.indexOf('base64,') + 7
			// 	that.upPicData.file = reader.result.substring(index)
			// 	that.upPic(that.upPicData, file)
			// }
			// return false
			
			// console.log('图片地址：' + JSON.stringify(images));
			// console.log('header里的' + JSON.stringify(oldImages));
			if (images.length > 0) {
				uni.uploadFile({
					url: 'http://120.27.63.37:38081/api/ac/file/fileCommonService/upLoadFiles',
					files: images,
					fileType: 'image',
					header: that.uploadFileHeader,
					success: res => {
						// _contentResult = JSON.parse(res.data); //转义字符 得到结果集
						console.log('上传图片成功' + res.data);
		
						var succData = JSON.parse(res.data);
						for (var i = 0; i < succData.data.length; i++) {
							oldImages.push(succData.data[i].path);
						}
						console.log(' 整理后图片地址' + oldImages);
						params.questionImg = oldImages.join(',');
						console.log('参数' + JSON.stringify(params));
						if (that.videoPath !== null) {
							that.uploadVideo(params);
						} else {
							that.reportEvent(params);
						}
					},
					fail: err => {
						console.log('uploadImage fail', err);
						uni.showModal({
							content: err.errMsg,
							showCancel: false
						});
					}
				});
			} else {
				params.questionImg = oldImages.join(',');
				console.log('参数' + JSON.stringify(params));
				if (that.videoPath !== null) {
					that.uploadVideo(params);
				} else {
					that.reportEvent(params);
				}
			}
		},
		// 上传相关
		beforeUpload (file, baseFile) {
		  var time = new Date().getTime()
		  this.timeStep = time.toString()
		  this.upPicData.fileName = this.formItem.log_title + this.timeStep + file.path.substring(file.path.lastIndexOf("."))
		  this.upPicData.filePath = this.timeStep
		  let that = this
		 //  const reader = new FileReader()
		 //  reader.readAsDataURL(file)
		 //  reader.onload = () => {
			// let index = reader.result.indexOf('base64,') + 7
			// console.log('look: xxxxxxxxxxxxxxxxxxx ============:', v)
			// console.log('look: xxxxxxxxxxxxxxxxxxx ============:', this.getBase64Image(v))
			// that.upPicData.file = reader.result.substring(index)
			// that.upPic(that.upPicData, file)
		 //  }
		  
		  let index = baseFile.indexOf('base64,') + 7
		  // console.log('look: xxxxxxxxxxxxxxxxxxx ============:', index)
		  that.upPicData.file = baseFile.substring(index)
		  that.upPic(that.upPicData, file)
		  return false
		},
		// 上传图片
		upPic (obj, file) {
		  var time = new Date().getTime()
		  this.timeStep = time.toString()
		  let param = {
			filePath: obj.filePath,
			fileName: obj.fileName,
			timestamp: this.timeStep
		  }
		  if (param.fileName.length > 20) {
			param.fileName = param.fileName.substring(0, 20) + file.path.substring(file.path.lastIndexOf(".")) 
		  }
		  this.$http.post('ac/xagrid/auditHadoopUploadFilesService/getSign', param).then(res => {
			// console.log('返回了数据你看看哪里：', res.errcode)
			if (res.errcode == 0) {
			  this.$http.post('ac/xagrid/auditHadoopUploadFilesService/createUpLoadFiles', 
			  { docking_url: res.data.docking_url, sign: res.data.sign, timestamp: this.timeStep, filePath: param.filePath, fileName: param.fileName, file: obj.file }
			  ).then(res => {
				if (res.errcode == 0) {
					// console.log('什么玩意啊： ', JSON.parse(res.data.uploadurl))
					let uri = JSON.parse(res.data.uploadurl)
					let Url = uri.data
					if (this.formItem.question_img === undefined || this.formItem.question_img.length === 0) {
					  this.formItem.question_img = Url
					} else {
					  this.formItem.question_img = this.formItem.question_img + ',' + Url
					}
					this.imageList.push(Url)
					this.index1 = this.imageList.length - 1
				} else {
					uni.showModal({
						title: '上传失败',
						content: res.msg,
						showCancel: false
					});
				}
			  })
			} else {
			  uni.showModal({
				title: '上传失败',
			  	content: res.msg,
			  	showCancel: false
			  });
			  // uni.showModal({
			  // 	title: '提示',
			  // 	content: '请输入日志标题',
			  // 	showCancel: false
			  // });
			}
		  })
		},
		uploadImages2(params) {
			var that = this;
			var oldImages = new Array();
			var images = new Array();
			for (var i = 0; i < that.imageList.length; i++) {
				var img = that.imageList[i];
				console.log('图片地址' + img);
				console.log('是否包含前缀' + img.indexOf('http://image.tripln.top/gridfile'));
				if (img.indexOf('http://image.tripln.top/gridfile') == 0) {
					oldImages.push(img.substr(32));
				} else {
					images.push({ name: 'images-' + String(i), uri: img });
				}
			}
			console.log('图片地址：' + JSON.stringify(images));
			console.log('header里的' + JSON.stringify(oldImages));
			if (images.length > 0) {
				uni.uploadFile({
					url: 'http://localhost:8081/api/xagrid/upload',
					files: images,
					fileType: 'image',
					header: that.uploadFileHeader,
					success: res => {
						// _contentResult = JSON.parse(res.data); //转义字符 得到结果集
						console.log('上传图片成功' + res.data);

						var succData = JSON.parse(res.data);
						for (var i = 0; i < succData.data.length; i++) {
							oldImages.push(succData.data[i].path);
						}
						console.log(' 整理后图片地址' + oldImages);
						params.questionImg = oldImages.join(',');
						console.log('参数' + JSON.stringify(params));
						if (that.videoPath !== null) {
							that.uploadVideo(params);
						} else {
							that.reportEvent(params);
						}
					},
					fail: err => {
						console.log('uploadImage fail', err);
						uni.showModal({
							content: err.errMsg,
							showCancel: false
						});
					}
				});
			} else {
				params.questionImg = oldImages.join(',');
				console.log('参数' + JSON.stringify(params));
				if (that.videoPath !== null) {
					that.uploadVideo(params);
				} else {
					that.reportEvent(params);
				}
			}
		},
		getDate(type) {
			const date = new Date();
			let year = date.getFullYear();
			let month = date.getMonth() + 1;
			let day = date.getDate();

			if (type === 'start') {
				year = year - 60;
			} else if (type === 'end') {
				year = year + 2;
			}
			month = month > 9 ? month : '0' + month;;
			day = day > 9 ? day : '0' + day;
			return `${year}-${month}-${day}`;
		},
		uploadVideo(params) {
			var that = this;
			if (that.videoPath.indexOf('http://image.tripln.top/gridfile') == 0) {
				var path = that.videoPath.substr(32);
				params.questionVideo = path;
				that.reportEvent(params);
			
			} else {
				uni.showLoading({title:'开始上传视频...'})
				uni.uploadFile({
					url: 'http://grid.tripln.top/api/xagrid/upload',
					fileType: 'video',
					filePath: that.videoPath,
					header: that.uploadFileHeader,
					name: 'data',
					success: res => {
						console.log('上传视频成功' + res.data);
						var succData = JSON.parse(res.data);
						params.questionVideo = succData.data[0].path;
						uni.hideLoading();
						that.reportEvent(params);
					},
					fail: ret => {
						uni.showToast({
							title:JSON.stringify(ret),
							icon:'none'
						})
					}
				});
			}
		},
		reportEvent(params) {
			uni.showLoading({title:'开始提交日志...'})
			//上传
			var url;
			if (this.eventId !== null) {
				//草稿箱提报
				url = 'ac/xagrid/appEventServiceImpl/updateEvent';
				params.id = this.eventId;
			} else {
				//新事件提报
				url = 'ac/xagrid/appEventServiceImpl/addEvent';
			}
			if(this.formItem.question_img.length > 0) {
				params.questionImg = this.formItem.question_img
			}
			this.$http.post(url, params).then(res => {
				uni.hideLoading();
				if (res.errcode === '0') {
					var tipStr;
					if (params.status === '0' || params.status === '2') {
						tipStr = '保存成功';
					} else {
						tipStr = '上报成功';
					}
					uni.showToast({
						title: tipStr,
						duration: 1500,
						complete() {
							setTimeout(function() {
								uni.navigateBack({});
							}, 1500);
						}
					});
				} else {
                  this.buttonFun()
					uni.showModal({
						title: '提示',
						content: res.errmsg,
						showCancel: false
					});
				}
			});
		},
		//草稿箱回显
		loadDraftData(id) {
			var self = this;
			this.$http.get('ac/xagrid/appEventServiceImpl/selectDraftsDetail', { id: id }).then(res => {
				self.eventDesc = res.data.questionContent;
				self.eventTitle = res.data.questionTitle;
				if (res.data.questionImg) {
					var images = res.data.questionImg.split(',');
					for (var i = 0; i < images.length; i++) {
						images[i] = 'http://image.tripln.top/gridfile' + images[i];
					}
					self.imageList = images;
					console.log('请求到的图片数组', JSON.stringify(self.imageList));
				}
				if (res.data.questionVideo) {
					var videoP = 'http://image.tripln.top/gridfile' + res.data.questionVideo;
					self.videoPath = videoP;
				}
				if (res.data.eventType === '1') {
					self.list[0].selectedValue = '1';
					self.list[0].selectedLabel = '企业事件';
					self.list[1].selectedValue = res.data.companyId;
					self.list[1].selectedLabel = res.data.companyName;
					self.list[2].selectedValue = res.data.taskType;
					self.list[2].selectedLabel = res.data.taskTypeName;
					self.list[3].selectedValue = res.data.targets_type;
					self.list[3].selectedLabel = res.data.targets_type_name;
					self.list[4].selectedValue = res.data.questionType;
					self.list[4].selectedLabel = res.data.questionTypeName;
				} else {
					self.list[0].selectedValue = '2';
					self.list[0].selectedLabel = '普通事件';
					// self.list.splice(1,1);
					self.list[1].selectedValue = res.data.taskType;
					self.list[1].selectedLabel = res.data.taskTypeName;
					self.list[2].selectedValue = res.data.targets_type;
					self.list[2].selectedLabel = res.data.targets_type_name;
					self.list[3].selectedValue = res.data.questionType;
					self.list[3].selectedLabel = res.data.questionTypeName;
				}
				self.location = { latitude: res.data.eventLatitude, longitude: res.data.eventLongitude };
			});
		}
	}
};
</script>

<style>
.viewBg {
	width: 100%;
	height: 100%;

	/* background-color: #0FAEFF; */
}

.cell-detail {
	margin-right: 20upx;
}
.uni-list-cell-navigate {
	justify-content: space-between;
}
.lineH20 {
	height: 20upx;
	/* width: 100%; */
	background-color: #f7f7f7;
}
.lineH1 {
	height: 2upx;
	/* width: 100%; */
	margin-left: 10upx;
	background-color: #f7f7f7;
}
.close-view {
	text-align: center;
	line-height: 14px;
	height: 16px;
	width: 16px;
	border-radius: 50%;
	background: #ff5053;
	color: #ffffff;
	position: absolute;
	top: -6px;
	right: -4px;
	font-size: 12px;
}
.button-sp-area {
	width: 40%;
}

map {
	width: 100%;
	height: 350upx;
	margin-top: 10upx;
	position: relative;
}

button {
	/* margin-top: 30upx; */
	/* margin-bottom: 30upx; */
	margin: 30upx;
}
</style>
